package com.leizi.igym.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leizi.igym.domain.Region;
import com.leizi.igym.enums.ReturnCodeEnum;
import com.leizi.igym.exception.BusinessException;
import com.leizi.igym.service.RegionService;
import com.leizi.igym.mapper.RegionMapper;
import com.leizi.igym.util.RedisUtils;
import com.leizi.igym.vo.RegionVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author PC
 * @description 针对表【t_region(区域表)】的数据库操作Service实现
 * @createDate 2024-04-09 09:28:35
 */
@Service
@Slf4j
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region>
        implements RegionService {

    /**
     * 查询所有区域
     *
     * @param
     * @return: java.util.List<com.leizi.igym.vo.RegionVO>
     **/
    @Override
    public List<RegionVO> getAll() {
        List<RegionVO> regionVOList;
        regionVOList = RedisUtils.get("ALL_REGION", List.class);
        if (Objects.nonNull(regionVOList)) {
            log.info("从redis获取区域列表,列表为：{}", regionVOList);
            return regionVOList;
        }
        regionVOList = this.getBaseMapper().selectList(null).stream().map(region -> {
            RegionVO regionVO = new RegionVO();
            BeanUtils.copyProperties(region, regionVO);
            return regionVO;
        }).collect(Collectors.toList());
        RedisUtils.set("ALL_REGION", regionVOList);
        return regionVOList;
    }

    @Override
    public RegionVO getByIdWithEquip(Long id) {
        if (Objects.isNull(id) || id <= 0) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR, "区域id有误！");
        }
        RegionVO regionVO = null;
        regionVO = RedisUtils.get("region::" + id, RegionVO.class);
        if (Objects.nonNull(regionVO)) {
            log.info("从redis获取区域,区域信息为：{}", regionVO);
            return regionVO;
        }
        regionVO = this.getBaseMapper().selectByIdWithEquip(id);
        RedisUtils.set("region::" + id, regionVO);
        return regionVO;
    }

    @Override
    public boolean updateRegion(Region region) {
        if (Objects.isNull(region)) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR);
        }
        Region dbRegion = this.getById(region);
        if (Objects.isNull(dbRegion)) {
            throw new BusinessException(ReturnCodeEnum.STATUS_ERROR, "该修改对象不存在！");
        }
        int i = this.getBaseMapper().updateById(region);
        if (i <= 0){
            return false;
        }
        RegionVO regionVO = this.getByIdWithEquip(region.getId());
        RedisUtils.set("region::"+regionVO.getId(),regionVO);
        return true;
    }

}




